package com.baizhiedu.mybatis;

import com.alibaba.druid.pool.DruidDataSource;
import org.mybatis.spring.SqlSessionFactoryBean;
import org.mybatis.spring.annotation.MapperScan;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.stereotype.Component;

import javax.sql.DataSource;
import java.io.IOException;

/**
 * ClassName: MyBatisConfiguration
 * Description:
 * Date: 2022/12/04 PM 4:22:49
 * <p>
 * project: spring5
 * package: com.baizhiedu.mybatis
 * email: 1085844536@qq.com
 * version:
 *
 * @author WangGuojian
 */
@Configuration
@ComponentScan(basePackages = "com.baizhiedu.mybatis")
@MapperScan(basePackages = "com.baizhiedu.mybatis")
public class MyBatisConfiguration {

    @Autowired
    private MyBatisProperties mybatisProperties;

    @Bean
    public DataSource dataSource() {
        DruidDataSource druidDataSource = new DruidDataSource();
        druidDataSource.setDriverClassName(mybatisProperties.getDriverClassName());
        druidDataSource.setUrl(mybatisProperties.getUrl());
        druidDataSource.setUsername(mybatisProperties.getUsername());
        druidDataSource.setPassword(mybatisProperties.getPassword());
        return druidDataSource;
    }

    @Bean
    public SqlSessionFactoryBean sqlSessionFactoryBean(DataSource dataSource) {
        SqlSessionFactoryBean sqlSessionFactoryBean = new SqlSessionFactoryBean();
        sqlSessionFactoryBean.setDataSource(dataSource);
        sqlSessionFactoryBean.setTypeAliasesPackage(mybatisProperties.getTypeAliasPackages());
        //sqlSessionFactoryBean.setMapperLocations(new ClassPathResource("UserDaoMapper.xml"));
        try {
            PathMatchingResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
            Resource[] resources = resolver.getResources(mybatisProperties.getMapperLocations());
            sqlSessionFactoryBean.setMapperLocations(resources);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
        return sqlSessionFactoryBean;
    }
}
